package com.sgb.kjwl.view.ui.activity.vehicleManagement;

import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.databinding.DataBindingUtil;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.SdkVersionUtils;
import com.sgb.capital.utils.Utils;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityAddDriverBinding;
import com.sgb.kjwl.di.vehicleManagement.AddVehicleModule;
import com.sgb.kjwl.di.vehicleManagement.DaggerAddVehicleComponent;
import com.sgb.kjwl.model.entity.self.CarInfoEntity;
import com.sgb.kjwl.model.entity.self.LicenceOCREntity;
import com.sgb.kjwl.model.entity.transport.DrivingLicenseOCREntity;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.DialogHelper;
import com.sgb.kjwl.utils.EntityConversion;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.utils.ImageUtil;
import com.sgb.kjwl.utils.MapUtils;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.RangeFocusChangeListener;
import com.sgb.kjwl.view.constant.RequestCode;
import com.sgb.kjwl.view.event.self.AuthEvent;
import com.sgb.kjwl.view.ui.activity.self.CameraActivity;
import com.sgb.kjwl.view.widget.ChoosePictureDialog;
import com.sgb.kjwl.view.widget.SwitchButton;
import com.sgb.kjwl.view.widget.transport.AMapDialog;
import com.sgb.kjwl.viewmodel.vehicleManagement.AddDriverAtvModel;
import com.sgb.link.entity.AMapAddressEntity;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.event.EventConstant;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.DeviceUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.NullableUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.List;

import javax.inject.Inject;

/**
 * 司机认证页
 * by wangbinchen
 */
@Route(path = AppRouteConstant.AddDriverInfoActivity)
public class AddDriverInfoActivity extends AppActivity {
    @Inject
    AddDriverAtvModel addDriverAtvModel;
    ActivityAddDriverBinding binding;
    public final int LICENSE_MAIN = 1;   //驾驶照正页
    public final int LICENSE_DEPUTY = 2;  //驾驶证副页
    private int type;
    String mUrlLicenseMain = "";
    String mUrlLicenseDeputy = "";
    String name;
    long id;
    String cardId;
    ChoosePictureDialog mChoosePictureDialog;
    LicenceOCREntity licenceOCREntity = new LicenceOCREntity();
    boolean manualCheck = false;
    private String address;
    public static final int TYPE_MAIN = 3;//主页
    public static final int TYPE_SUB = 4;  //副页
    public static final int TYPE_ACTUAL = 5;//车辆45度图
    //选择图片类型 1:主页 2:副页 3:车辆45度图
    private int mType;

    public int ADDRESS_TYPE = 0;  //选择地址
    public final int ADDRESS_DRIVER = 1;   //选择司机地址
    public final int ADDRESS_CAR = 2;  //选择车辆地址


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerAddVehicleComponent.builder().appComponent(appComponent).addVehicleModule(new AddVehicleModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_add_driver);
        binding.setViewModel(addDriverAtvModel);
        binding.include.titleView.setText("司机-车辆认证");
        binding.include.ivBack.setOnClickListener(this);
        binding.nextView.setOnClickListener(this);
        binding.ivMain.setOnClickListener(this);
        binding.ivDeputy.setOnClickListener(this);
        binding.deleteMainPic.setOnClickListener(this);
        binding.deleteDeputyPic.setOnClickListener(this);
        binding.llAddress.setOnClickListener(this);
        initEvent();

        name = getIntent().getStringExtra("name");
        id = getIntent().getLongExtra("id", 0);
        cardId = getIntent().getStringExtra("cardId");

        mUrlLicenseMain = getIntent().getStringExtra("licenseMain") == null ? "" : getIntent().getStringExtra("licenseMain");
        mUrlLicenseDeputy = getIntent().getStringExtra("licenseDeputy") == null ? "" : getIntent().getStringExtra("licenseDeputy");

        initLicenceView();
        addDriverAtvModel.ldCar.postValue(new CarInfoEntity());
        addDriverAtvModel.ldOcr.postValue(new DrivingLicenseOCREntity());

        //编辑司机认证时不展示车辆认证信息
        if (TextUtils.isEmpty(mUrlLicenseMain)) {
            binding.clUploadCarLayout.setVisibility(View.VISIBLE);
            binding.switchDefault.setmOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
                @Override
                public void OnCheckedChanged(boolean isChecked) {
                    if (isChecked) {
                        binding.llAddCar.setVisibility(View.VISIBLE);
                    } else {
                        binding.llAddCar.setVisibility(View.GONE);
                    }
                }
            });
        } else {
            binding.clUploadCarLayout.setVisibility(View.GONE);
        }
    }

    private void initEvent() {
        binding.setOnClick(this);
        //设置输入范围，失去焦点后自动补全
        binding.etAddCarWeight.setOnFocusChangeListener(new RangeFocusChangeListener(1, 999999999));
        binding.etAddCarLength.setOnFocusChangeListener(new RangeFocusChangeListener(1, 999999));
        //接口回调
        addDriverAtvModel.ldMain.observe(this, url -> {
            if (!TextUtils.isEmpty(url)) {
                binding.imgDel1.setVisibility(View.VISIBLE);
            } else {
                binding.imgDel1.setVisibility(View.GONE);
            }
            NullableUtil.ofNullable(addDriverAtvModel.ldCar.getValue()).ifPresent(carInfoEntity -> carInfoEntity.setVehicleLicense(url));
            showImage(binding.ivAddCarMain, url);
        });
        addDriverAtvModel.ldSub.observe(this, url -> {
            if (!TextUtils.isEmpty(url)) {
                binding.imgDel2.setVisibility(View.VISIBLE);
            } else {
                binding.imgDel2.setVisibility(View.GONE);
            }
            NullableUtil.ofNullable(addDriverAtvModel.ldCar.getValue()).ifPresent(carInfoEntity -> carInfoEntity.setDrivingLicensePage(url));
            showImage(binding.ivAddCarSub, url);
        });
        addDriverAtvModel.ldActual.observe(this, url -> {
            if (!TextUtils.isEmpty(url)) {
                binding.imgDel3.setVisibility(View.VISIBLE);
            } else {
                binding.imgDel3.setVisibility(View.GONE);
            }
            NullableUtil.ofNullable(addDriverAtvModel.ldCar.getValue()).ifPresent(carInfoEntity -> carInfoEntity.setCarImage(url));
            showImage(binding.ivAddCarActual, url);
        });
        //车辆详情信息
        addDriverAtvModel.ldCar.observe(this, carInfoEntity -> {
            if (carInfoEntity == null || carInfoEntity.getId() == 0) {
                return;
            }
            try {
                if (!TextUtils.isEmpty(carInfoEntity.getVehicleLicense())) {
                    binding.imgDel1.setVisibility(View.VISIBLE);
                } else {
                    binding.imgDel1.setVisibility(View.GONE);
                }
                if (!TextUtils.isEmpty(carInfoEntity.getDrivingLicensePage())) {
                    binding.imgDel2.setVisibility(View.VISIBLE);
                } else {
                    binding.imgDel2.setVisibility(View.GONE);
                }
                if (!TextUtils.isEmpty(carInfoEntity.getCarImage())) {
                    binding.imgDel3.setVisibility(View.VISIBLE);
                } else {
                    binding.imgDel3.setVisibility(View.GONE);
                }
                showImage(binding.ivAddCarMain, carInfoEntity.getVehicleLicense(), false);
                showImage(binding.ivAddCarSub, carInfoEntity.getDrivingLicensePage(), false);
                showImage(binding.ivAddCarActual, carInfoEntity.getCarImage(), false);
                //ocr车辆数据
                DrivingLicenseOCREntity ocrEntity = EntityConversion.modelA2B(carInfoEntity, DrivingLicenseOCREntity.class);
                if (ocrEntity == null) {
                    ocrEntity = new DrivingLicenseOCREntity();
                }
                addDriverAtvModel.ldOcr.postValue(ocrEntity);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
        //ocr识别结果
        addDriverAtvModel.ldOcr.observe(this, entity -> {
            if (entity == null) return;
            try {
                //ocr反显
                binding.llAddCarCheck.setVisibility(View.VISIBLE);
                binding.etAddCarNumber.setText(DefaultUtil.getString(entity.getImageCarNumber()));
                binding.etAddCarWeight.setText(TextUtils.isEmpty(entity.getImageApprovedLoadingQuality())
                        ? ""
                        : NumberUtil.trim0(entity.getImageApprovedLoadingQuality()));
                binding.etAddCarLength.setText(TextUtils.isEmpty(entity.getImageSizeL())
                        ? ""
                        : NumberUtil.trim0(entity.getImageSizeL()));
                binding.tvAddressCar.setText(TextUtils.isEmpty(entity.getImageVehicleAddress())
                        ? ""
                        : entity.getImageVehicleAddress());
                binding.archivesNumberCar.setText(entity.getImageNumber());
                MapUtils.searchByLocationName(this, addDriverAtvModel.ldOcr.getValue().getImageVehicleAddress(), new MapUtils.OnMapSearchListener() {
                    @Override
                    public void onGeocodeSearched(com.sgb.kjwl.model.entity.transport.AMapAddressEntity aMapAddressEntity) {
                        if (aMapAddressEntity != null) {
                            try {
                                addDriverAtvModel.ldCar.getValue().setImageVehicleLat(aMapAddressEntity.getLatitude());
                                addDriverAtvModel.ldCar.getValue().setImageVehicleLon(aMapAddressEntity.getLongitude());
                                addDriverAtvModel.ldCar.getValue().setProvinceName(aMapAddressEntity.getProvince());
                                addDriverAtvModel.ldCar.getValue().setProvinceNo(aMapAddressEntity.getProvinceNo());
                                addDriverAtvModel.ldCar.getValue().setCityName(aMapAddressEntity.getCity());
                                addDriverAtvModel.ldCar.getValue().setCityNo(aMapAddressEntity.getCityNo());
                                addDriverAtvModel.ldCar.getValue().setDistrictName(aMapAddressEntity.getDistrict());
                                addDriverAtvModel.ldCar.getValue().setDistrictNo(aMapAddressEntity.getDistrictNo());
                                addDriverAtvModel.ldCar.getValue().setDetailAddress(aMapAddressEntity.getSnippet());
                            } catch (Exception e) {

                            }

                        }
                    }

                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void initLicenceView() {
        float ratio = 165f / 375f;
        float widthHeightRatio = 165f / 100f;
        float imageWidth = DeviceUtils.getScreenPix(this).widthPixels * ratio;
        float height = imageWidth / widthHeightRatio;

        ((RelativeLayout.LayoutParams) binding.ivMain.getLayoutParams()).height = (int) height;
        ((RelativeLayout.LayoutParams) binding.ivDeputy.getLayoutParams()).height = (int) height;
        ((RelativeLayout.LayoutParams) binding.ivMain.getLayoutParams()).width = (int) imageWidth;
        ((RelativeLayout.LayoutParams) binding.ivDeputy.getLayoutParams()).width = (int) imageWidth;

        if (!mUrlLicenseMain.isEmpty()) {
            RequestOptions options = new RequestOptions()
                    .dontAnimate()
                    .placeholder(R.drawable.img_license_main)
                    .error(R.drawable.car_place_img)
                    .centerCrop();
            Glide.with(this).load(mUrlLicenseMain).apply(options).into(binding.ivMain);
            binding.deleteMainPic.setVisibility(View.VISIBLE);
        }
        if (!mUrlLicenseDeputy.isEmpty()) {
            RequestOptions options = new RequestOptions()
                    .dontAnimate()
                    .placeholder(R.drawable.img_license_deputy)
                    .error(R.drawable.car_place_img)
                    .centerCrop();
            Glide.with(this).load(mUrlLicenseDeputy).apply(options).into(binding.ivDeputy);
            binding.deleteDeputyPic.setVisibility(View.VISIBLE);
        }
        getOCRLicenceInfo();
        addDriverAtvModel.getLocation(this);
    }

    @Override
    public void onClick(View v) {
        int vId = v.getId();
        if (vId == R.id.iv_back) {
            DialogHelper.showDialog(AddDriverInfoActivity.this, "提示", "您确定要暂停认证司机吗？",
                    "确定", new DialogFunction() {
                        @Override
                        public void normalRoundDialog() {
                            finish();
                        }
                    });
        } else if (vId == R.id.delete_main_pic) {
            mUrlLicenseMain = "";
            binding.ivMain.setImageDrawable(getResources().getDrawable(R.drawable.img_license_main));
            binding.deleteMainPic.setVisibility(View.GONE);
        } else if (vId == R.id.delete_deputy_pic) {
            mUrlLicenseDeputy = "";
            binding.ivDeputy.setImageDrawable(getResources().getDrawable(R.drawable.img_license_deputy));
            binding.deleteDeputyPic.setVisibility(View.GONE);
        } else if (vId == R.id.iv_main) {
            mChoosePictureDialog = new ChoosePictureDialog(getActivity(), R.drawable.img_license_main_no_camera);
            mChoosePictureDialog.setDialogClickCallBack(new ChoosePictureDialog.DialogClickCallBack() {
                @Override
                public void onItemClick(String ids) {
                    if (ids.equals("拍照")) {
                        startCamera(LICENSE_MAIN);
                    } else if (ids.equals("从手机相册选择")) {
                        getCerImage(LICENSE_MAIN);
                    }

                }
            });
            mChoosePictureDialog.show(getSupportFragmentManager(), "1");
        } else if (vId == R.id.iv_deputy) {
            mChoosePictureDialog = new ChoosePictureDialog(getActivity(), R.drawable.img_license_deputy_no_camera);
            mChoosePictureDialog.setDialogClickCallBack(new ChoosePictureDialog.DialogClickCallBack() {
                @Override
                public void onItemClick(String ids) {
                    if (ids.equals("拍照")) {
                        startCamera(LICENSE_DEPUTY);
                    } else if (ids.equals("从手机相册选择")) {
                        getCerImage(LICENSE_DEPUTY);
                    }
                }
            });
            mChoosePictureDialog.show(getSupportFragmentManager(), "2");
        } else if (vId == R.id.next_view) {
            ClickUtils.setSpaceTimes(3000);
            if (ClickUtils.isDoubleClick2()) {
                return;
            }
            if (mUrlLicenseMain.equals("")) {
                MToast.showToast(this, "请先上传驾驶证主页");
                return;
            }
            if (mUrlLicenseDeputy.equals("")) {
                MToast.showToast(this, "请先上传驾驶证副页");
                return;
            }

            if (!checkOcrInfoIsValid()) {
                return;
            }

            if (binding.switchDefault.isChecked()) {//上传车辆
                clearAllFocus();
                //重新设置页面车辆信息
                NullableUtil.ofNullable(addDriverAtvModel.ldCar.getValue()).ifPresent(carInfoEntity -> {
                    if (binding.etAddCarNumber.getText() != null) {
                        carInfoEntity.setCarNumber(binding.etAddCarNumber.getText().toString());
                    } else {
                        carInfoEntity.setCarNumber(null);
                    }
                    if (binding.etAddCarWeight.getText() != null) {
                        carInfoEntity.setImageApprovedLoadingQuality(binding.etAddCarWeight.getText().toString());
                    } else {
                        carInfoEntity.setImageApprovedLoadingQuality(null);
                    }
                    if (binding.etAddCarLength.getText() != null) {
                        carInfoEntity.setCarLen(NumberUtil.convertToDouble(binding.etAddCarLength.getText().toString()));
                    } else {
                        carInfoEntity.setCarLen(0);
                    }
                    if (binding.carOwner.getText() != null) {
                        carInfoEntity.setLinkman(binding.carOwner.getText().toString());
                    } else {
                        carInfoEntity.setLinkman(null);
                    }
                    if (binding.ownerPhone.getText() != null) {
                        carInfoEntity.setLinkmanPhone(binding.ownerPhone.getText().toString());
                    } else {
                        carInfoEntity.setLinkmanPhone(null);
                    }

                });
                if (!TextUtils.isEmpty(binding.archivesNumberCar.getText().toString())) {
                    addDriverAtvModel.ldOcr.getValue().setImageNumber(binding.archivesNumberCar.getText().toString());
                    addDriverAtvModel.ldCar.getValue().setImageNumber(binding.archivesNumberCar.getText().toString());
                } else {
                    if (addDriverAtvModel.ldOcr.getValue() == null) {
                        addDriverAtvModel.ldOcr.setValue(new DrivingLicenseOCREntity());
                    }
                    addDriverAtvModel.ldOcr.getValue().setImageNumber("");
                    addDriverAtvModel.ldCar.getValue().setImageNumber("");
                }

                if (addDriverAtvModel.ldCar.getValue() == null) return;
                String main = addDriverAtvModel.ldCar.getValue().getVehicleLicense();
                if (TextUtils.isEmpty(main)) {
                    MToast.showToast(this, "请先上传行驶证主页");
                    return;
                }
                String sub = addDriverAtvModel.ldCar.getValue().getDrivingLicensePage();
                if (TextUtils.isEmpty(sub)) {
                    MToast.showToast(this, "请先上传行驶证副页");
                    return;
                }
//                String car = addDriverAtvModel.ldCar.getValue().getCarImage();
//        if (TextUtils.isEmpty(car)) {
//            MToast.showToast(this, "请先上传车辆45度照片");
//            return;
//        }
                if (TextUtils.isEmpty(addDriverAtvModel.ldCar.getValue().getCarNumber())) {
                    MToast.showToast(this, "请先输入车牌号");
                    return;
                }
                if (!Utils.isPlateLogistics(addDriverAtvModel.ldCar.getValue().getCarNumber())){
                    MToast.showToast(this, "请输入正确的车牌号");
                    return;
                }
                if (TextUtils.isEmpty(addDriverAtvModel.ldCar.getValue().getImageApprovedLoadingQuality())) {
                    MToast.showToast(this, "请先输入核定载质量");
                    return;
                }
                if (addDriverAtvModel.ldCar.getValue().getCarLen() == 0) {
                    MToast.showToast(this, "请先输入车长");
                    return;
                }
                if (TextUtils.isEmpty(addDriverAtvModel.ldCar.getValue().getDetailAddress())) {
                    MToast.showToast(this, "请先输入住址");
                    return;
                }

                if (!TextUtils.isEmpty(addDriverAtvModel.ldCar.getValue().getImageNumber())) {
                    if (addDriverAtvModel.ldCar.getValue().getImageNumber().length() != 12) {
                        MToast.showToast(this, "请输入12位档案编号.");
                        return;
                    }
                }
                if (TextUtils.isEmpty(addDriverAtvModel.ldCar.getValue().getLinkman())) {
                    MToast.showToast(this, "请先输入车辆负责人");
                    return;
                }
                if (TextUtils.isEmpty(addDriverAtvModel.ldCar.getValue().getLinkmanPhone())) {
                    MToast.showToast(this, "请先输入负责人电话");
                    return;
                }

                addDriverAtvModel.authDriver(id,
                        licenceOCREntity,
                        binding.name.getText().toString(),
                        binding.licenceNumber.getText().toString(),
                        binding.archivesNumber.getText().toString(),
                        mUrlLicenseMain, mUrlLicenseDeputy, manualCheck);

                if (addDriverAtvModel.ldCar != null && TextUtils.isEmpty(addDriverAtvModel.ldCar.getValue().getDetailAddress())) {
                    if (TextUtils.isEmpty(addDriverAtvModel.ldOcr.getValue().getImageVehicleAddress())) {
                        addDriverAtvModel.authCar(this, binding.licenceNumber.getText().toString(), binding.name.getText().toString(), mUrlLicenseMain, mUrlLicenseDeputy);
                        return;
                    }
                    MapUtils.searchByLocationName(this, addDriverAtvModel.ldOcr.getValue().getImageVehicleAddress(), new MapUtils.OnMapSearchListener() {
                        @Override
                        public void onGeocodeSearched(com.sgb.kjwl.model.entity.transport.AMapAddressEntity aMapAddressEntity) {
                            if (aMapAddressEntity != null) {
                                try {
                                    addDriverAtvModel.ldCar.getValue().setImageVehicleLat(aMapAddressEntity.getLatitude());
                                    addDriverAtvModel.ldCar.getValue().setImageVehicleLon(aMapAddressEntity.getLongitude());
                                    addDriverAtvModel.ldCar.getValue().setProvinceName(aMapAddressEntity.getProvince());
                                    addDriverAtvModel.ldCar.getValue().setProvinceNo(aMapAddressEntity.getProvinceNo());
                                    addDriverAtvModel.ldCar.getValue().setCityName(aMapAddressEntity.getCity());
                                    addDriverAtvModel.ldCar.getValue().setCityNo(aMapAddressEntity.getCityNo());
                                    addDriverAtvModel.ldCar.getValue().setDistrictName(aMapAddressEntity.getDistrict());
                                    addDriverAtvModel.ldCar.getValue().setDistrictNo(aMapAddressEntity.getDistrictNo());
                                    addDriverAtvModel.ldCar.getValue().setDetailAddress(aMapAddressEntity.getSnippet());
                                    addDriverAtvModel.authCar(AddDriverInfoActivity.this, binding.licenceNumber.getText().toString(), binding.name.getText().toString(), mUrlLicenseMain, mUrlLicenseDeputy);
                                } catch (Exception e) {

                                }

                            }
                        }

                    });
                } else {
                    addDriverAtvModel.authCar(this, binding.licenceNumber.getText().toString(), binding.name.getText().toString(), mUrlLicenseMain, mUrlLicenseDeputy);
                }

            } else {
                addDriverAtvModel.authDriver(id,
                        licenceOCREntity,
                        binding.name.getText().toString(),
                        binding.licenceNumber.getText().toString(),
                        binding.archivesNumber.getText().toString(),
                        mUrlLicenseMain, mUrlLicenseDeputy, manualCheck);
            }
        } else if (vId == R.id.ll_address) {
            ADDRESS_TYPE = ADDRESS_DRIVER;
            AMapDialog.launch(this, licenceOCREntity.getLatitude(), licenceOCREntity.getLongitude());
        } else if (v == binding.flAddCarMain) {
            showPictureDialog(R.drawable.img_xszy, TYPE_MAIN);
        } else if (v == binding.flAddCarSub) {
            showPictureDialog(R.drawable.img_xszfy, TYPE_SUB);
        } else if (v == binding.flAddCarActual) {
            showPictureDialog(R.drawable.img_sl_car, TYPE_ACTUAL);
        } else if (v == binding.imgDel1) {
            addDriverAtvModel.ldMain.postValue("");
        } else if (v == binding.imgDel2) {
            addDriverAtvModel.ldSub.postValue("");
        } else if (v == binding.imgDel3) {
            addDriverAtvModel.ldActual.postValue("");
        } else if (v == binding.llAddressCar) {
            ADDRESS_TYPE = ADDRESS_CAR;
            AMapDialog.launch(this, addDriverAtvModel.ldCar.getValue().getImageVehicleLat(), addDriverAtvModel.ldCar.getValue().getImageVehicleLon());
        }
    }

    /**
     * 图片选择
     */
    private void showPictureDialog(int pic, int type) {
        ChoosePictureDialog dialog = new ChoosePictureDialog(this, pic);
        dialog.setDialogClickCallBack(ids -> {
            if ("拍照".equals(ids)) {
                getTackPhoto(type);
            } else if ("从手机相册选择".equals(ids)) {
                getCerImage(type);
            }
        });
        dialog.show(getSupportFragmentManager(), "pic");
    }

    /**
     * 拍照
     */
    private void getTackPhoto(int type) {
        this.type = type;
        mType = type;
        if (mType == TYPE_MAIN) {
            CameraActivity.start(this, 1, "行驶证主页", PictureConfig.REQUEST_CAMERA);
        } else if (mType == TYPE_SUB) {
            CameraActivity.start(this, 1, "行驶证副页", PictureConfig.REQUEST_CAMERA);
        } else if (mType == TYPE_ACTUAL) {
            PictureSelector.create(this)
                    .openCamera(PictureMimeType.ofImage())
                    .loadImageEngine(GlideEngine.createGlideEngine())
                    .theme(R.style.picture_default_style)
                    .compress(true)//是否压缩
                    .minimumCompressSize(4 * 1024)//小于4M不压缩
                    .forResult(PictureConfig.CHOOSE_REQUEST);
        }
    }

    private boolean checkOcrInfoIsValid() {
        if (TextUtils.isEmpty(binding.name.getText())) {
            MToast.showToast(this, "请先输入姓名");
            return false;
        }
        if (TextUtils.isEmpty(binding.licenceNumber.getText()) || !CheckUtils.isVersionTwoIDNumber(binding.licenceNumber.getText().toString())) {
            MToast.showToast(this, "请输入正确格式的驾驶证证号");
            return false;
        }
        if (TextUtils.isEmpty(binding.archivesNumber.getText()) || !CheckUtils.isDriveFileNumber(binding.archivesNumber.getText().toString())) {
            MToast.showToast(this, "请输入正确格式的档案编号");
            return false;
        }
        return true;
    }

    private void getCerImage(int type) {
        this.type = type;
        mType = type;
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .selectionMode(PictureConfig.SINGLE)
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .compress(true)//是否压缩
                .minimumCompressSize(4 * 1024)//小于4M不压缩
                .maxSelectNum(1)//判断还能选多少张图片
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            String path = "";
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    File file = new File(selectList.get(0).getRealPath());
                    MLog.d("图片路径：", selectList.get(0).getRealPath());
                    if (file.exists()) {
                        MLog.d("图片", "存在");
                    }
                    if (LICENSE_MAIN == type) {
                        Glide.with(getActivity()).load(file).into(binding.ivMain);
                        binding.deleteMainPic.setVisibility(View.VISIBLE);
                        addDriverAtvModel.uploadMutiFileModel(ImageUtil.getImage(selectList.get(0).getRealPath()), LICENSE_MAIN);
                    } else if (type == LICENSE_DEPUTY) {
                        //Bugly报file为空
                        if (file.length() > 0) {
                            Glide.with(getActivity()).load(file).into(binding.ivDeputy);
                            binding.deleteDeputyPic.setVisibility(View.VISIBLE);
                        }
                        if (!TextUtils.isEmpty(selectList.get(0).getRealPath())) {
                            addDriverAtvModel.uploadMutiFileModel(ImageUtil.getImage(selectList.get(0).getRealPath()), LICENSE_DEPUTY);
                        }
                    }

                    if (selectList == null || selectList.size() == 0) return;
                    //获取压缩图片
                    if (SdkVersionUtils.checkedAndroid_Q()) {
                        path = selectList.get(0).getAndroidQToPath();
                    } else {
                        path = selectList.get(0).getCompressPath();
                    }
                    if (TextUtils.isEmpty(path)) {
                        return;
                    }
                    switch (mType) {
                        case TYPE_MAIN:
                            addDriverAtvModel.uploadFileWithOCR(this, new File(path));
                            break;
                        case TYPE_SUB:
                        case TYPE_ACTUAL:
                            addDriverAtvModel.uploadFile(this, new File(path), mType);
                            break;
                    }
                    break;
                case PictureConfig.REQUEST_CAMERA:
                    path = data.getStringExtra("imagePath");
                    File takePictureFile = new File(path);
                    if (LICENSE_MAIN == type) {
                        Glide.with(getActivity()).load(takePictureFile).into(binding.ivMain);
                        addDriverAtvModel.uploadMutiFileModel(ImageUtil.getImage(path), LICENSE_MAIN);
                    } else if (type == LICENSE_DEPUTY) {
                        //Bugly报file为空
                        if (takePictureFile.length() > 0) {
                            Glide.with(getActivity()).load(takePictureFile).into(binding.ivDeputy);
                        }
                        if (!TextUtils.isEmpty(path)) {
                            addDriverAtvModel.uploadMutiFileModel(ImageUtil.getImage(path), LICENSE_DEPUTY);
                        }
                    }
                    if (TextUtils.isEmpty(path)) {
                        return;
                    }
                    switch (mType) {
                        case TYPE_MAIN:
                            addDriverAtvModel.uploadFileWithOCR(this, new File(path));
                            break;
                        case TYPE_SUB:
                        case TYPE_ACTUAL:
                            addDriverAtvModel.uploadFile(this, new File(path), mType);
                            break;
                    }
                    break;
                case RequestCode.CODE_MAP:
                    AMapAddressEntity entity = AMapDialog.get(data);
                    if (entity.getSnippet().contains("省") && entity.getSnippet().contains("市")) {
                        address = entity.getSnippet();
                    } else {
                        address = entity.getAllProvince() + entity.getAllCity() + entity.getAllDistrict() + entity.getSnippet();
                    }
                    if (ADDRESS_TYPE == ADDRESS_DRIVER) {
                        binding.tvAddress.setText(address);
                        licenceOCREntity.setDetailAddress(address);
                        licenceOCREntity.setLatitude(entity.getLatitude());
                        licenceOCREntity.setLongitude(entity.getLongitude());
                        licenceOCREntity.setProvinceNo(entity.getProvinceNo());
                        licenceOCREntity.setProvinceName(entity.getAllProvince());
                        licenceOCREntity.setCityName(entity.getAllCity());
                        licenceOCREntity.setCityNo(entity.getCityNo());
                        licenceOCREntity.setDistrictName(entity.getAllDistrict());
                        licenceOCREntity.setDistrictNo(entity.getDistrictNo());
                    } else if (ADDRESS_TYPE == ADDRESS_CAR) {
                        binding.tvAddressCar.setText(address);
                        addDriverAtvModel.ldCar.getValue().setImageVehicleLat(entity.getLatitude());
                        addDriverAtvModel.ldCar.getValue().setImageVehicleLon(entity.getLongitude());
                        addDriverAtvModel.ldCar.getValue().setProvinceName(entity.getProvince());
                        addDriverAtvModel.ldCar.getValue().setProvinceNo(entity.getProvinceNo());
                        addDriverAtvModel.ldCar.getValue().setCityName(entity.getCity());
                        addDriverAtvModel.ldCar.getValue().setCityNo(entity.getCityNo());
                        addDriverAtvModel.ldCar.getValue().setDistrictName(entity.getDistrict());
                        addDriverAtvModel.ldCar.getValue().setDistrictNo(entity.getDistrictNo());
                        addDriverAtvModel.ldCar.getValue().setDetailAddress(address);
                        addDriverAtvModel.ldOcr.getValue().setImageVehicleAddress(address);
                    }
                    break;
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            DialogHelper.showDialog(AddDriverInfoActivity.this, "提示", "您确定要暂停认证司机吗？",
                    "确定", new DialogFunction() {
                        @Override
                        public void normalRoundDialog() {
                            finish();
                        }
                    });
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void showOCRInfo(LicenceOCREntity licenceOCREntity) {
        //每次调用OCR识别后第一次提交如果与实名信息不同的时候，都提示用户与实名信息不符
        manualCheck = false;
        this.licenceOCREntity = licenceOCREntity;
        setTextInfo(licenceOCREntity.getImageName(), licenceOCREntity.getImageIdCard(), licenceOCREntity.getImageFileNumber(), licenceOCREntity.getDetailAddress());
    }

    private void setTextInfo(String name, String idCard, String fileNumber, String address) {
        binding.infoLayout.setVisibility(View.VISIBLE);
//        binding.tipsText.setVisibility(View.VISIBLE);
        binding.name.setText(name);
        binding.licenceNumber.setText(idCard);
        binding.archivesNumber.setText(fileNumber);
        binding.tvAddress.setText(address);
        this.address = address;
        MapUtils.searchByLocationName(this, licenceOCREntity.getDetailAddress(), new MapUtils.OnMapSearchListener() {
            @Override
            public void onGeocodeSearched(com.sgb.kjwl.model.entity.transport.AMapAddressEntity aMapAddressEntity) {
                if (aMapAddressEntity != null) {
                    licenceOCREntity.setProvinceName(aMapAddressEntity.getAllProvince());
                    licenceOCREntity.setProvinceNo(aMapAddressEntity.getProvinceNo());
                    licenceOCREntity.setCityName(aMapAddressEntity.getAllCity());
                    licenceOCREntity.setCityNo(aMapAddressEntity.getCityNo());
                    licenceOCREntity.setDistrictName(aMapAddressEntity.getAllDistrict());
                    licenceOCREntity.setDistrictNo(aMapAddressEntity.getDistrictNo());
                }
            }
        });

    }

    public void oCRFail() {
        showNoticeDialog("证照无法识别，可重新上传或填写后提交人工审核");
        licenceOCREntity.setLatitude(0);
        licenceOCREntity.setLatitude(0);
        setTextInfo("", "", "", "");

    }

    public void oCRSuccess(LicenceOCREntity licenceOCREntity) {
        showOCRInfo(licenceOCREntity);
    }


    //展示提示弹窗
    public void showNoticeDialog(String notice) {
        new RoundDialog.Builder(this)
                .title("提示")
                .content(notice)
                .singleBtn(true)
                .confirm("确定")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .show();
    }

    public void showRealNameIsDifferentWithOCRInfo(String text) {
        new RoundDialog.Builder(this)
                .title("提示")
                .content(text)
                .cancel("提交")
                .confirm("暂不提交")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .cancelCallback(v -> {
                    //实名信息于OCR识别的信息不符，可以点击可以强制提交人工审核
                    manualCheck = true;
                    addDriverAtvModel.authDriver(id,
                            licenceOCREntity,
                            binding.name.getText().toString(),
                            binding.licenceNumber.getText().toString(),
                            binding.archivesNumber.getText().toString(),
                            mUrlLicenseMain, mUrlLicenseDeputy, manualCheck);
                }).show();
    }


    public void uploadImgSuccess(String urls, int type) {
        if (type == LICENSE_MAIN) {
            mUrlLicenseMain = urls;
        } else if (type == LICENSE_DEPUTY) {
            mUrlLicenseDeputy = urls;
        }
        getOCRLicenceInfo();
    }

    private void getOCRLicenceInfo() {
        if (!TextUtils.isEmpty(mUrlLicenseDeputy) && !TextUtils.isEmpty(mUrlLicenseMain)) {
            addDriverAtvModel.getOCRLicenceInfo(mUrlLicenseMain, mUrlLicenseDeputy);
        }
    }

    public void addSuccess() {
        finish();
        EventBus.getDefault().postSticky(AuthEvent.make(EventConstant.EVENT_REFRESH_DRIVER_AUTH_, null));
        DriverInfoActivity.start(this);
    }


    private void startCamera(int type) {
        this.type = type;
        mType = type;
        if (this.type == LICENSE_MAIN) {
            CameraActivity.start(this, 0, "驾驶证主页", PictureConfig.REQUEST_CAMERA);
        } else {
            CameraActivity.start(this, 1, "驾驶证副页", PictureConfig.REQUEST_CAMERA);
        }
    }

    /**
     * 展示图片
     */
    private void showImage(ImageView imageView, String path) {
        showImage(imageView, path, true);
    }

    private void showImage(ImageView imageView, String path, boolean checkOcr) {
        if (TextUtils.isEmpty(path)) {
            imageView.setImageResource(R.color.transparent);
            imageView.setBackgroundColor(Color.TRANSPARENT);
            return;
        }
        imageView.setBackgroundColor(Color.WHITE);
        Glide.with(this).load(path)
                .apply(new RequestOptions().centerCrop())
                .into(imageView);
        //车辆图片不触发ocr识别
        if (mType == TYPE_ACTUAL) return;
        //检查是否进行ocr
        if (checkOcr && addDriverAtvModel.ldCar.getValue() != null
                && !TextUtils.isEmpty(addDriverAtvModel.ldCar.getValue().getVehicleLicense())
                && !TextUtils.isEmpty(addDriverAtvModel.ldCar.getValue().getDrivingLicensePage())) {
            addDriverAtvModel.carOcr(this);
        }
    }

}

